#include <iostream>
#include <cstdio>
#include <boost/algorithm/string.hpp>
#include <boost/timer.hpp>
#include "Interpreter.h"

using namespace std;

Interpreter GeekunInterpreter;

bool login() {
    API *api = GeekunInterpreter.api;
    api->AddUser("root", "root", "A");
    for (int t = 0; t < 10; ++t) {
        string username, password;
        printf("Input UserName: ");
        cin >> username;
        printf("Input PassWord: ");
        cin >> password;
        if (api->ValidUser(username, password).empty()) {
            cout << "Invalide UserName Or PassWord!" << endl;
        } else {
            cout << "Successfully Login. Welcome To " << username << " " << endl;
            return true;
        }
    }
    return false;
}

void run() {
    string sql;
    string line;
    size_t end;
    while (true) {
        cout << endl << ">>> ";
        cout.flush();
        getline(cin, line);
        sql = string(line);
        if (sql == "") { continue; }
        boost::algorithm::trim(sql);
        if (sql.compare(0, 4, "exit") == 0 || sql.compare(0, 4, "quit") == 0 || sql.compare(0, 2, "\\q") == 0 ||
            sql.compare(0, 2, "\\e") == 0) {
            GeekunInterpreter.ExecSQL("quit");
            break;
        }
        while ((end = sql.find(";")) == string::npos) {
            cout << "> ";
            getline(cin, line);
            if (line == "") { continue; }
            sql += "\n" + string(line);
        }
        boost::timer ter;
        GeekunInterpreter.ExecSQL(sql);
        cout << "[Cost Time: " << ter.elapsed() << " second.]" << endl;
    }
}

int main() {
    if (login())
        run();
    return 0;
}
